import axios from 'axios';
import { message } from 'antd';
import { history } from 'umi';

const newIntances = axios.create({
  baseURL: 'http://xawn.f3322.net:8012',
  timeout: 3000,
});

//请求拦截器
newIntances.interceptors.request.use(
  (req: any) => {
    // console.log(req);

    //给请求头设置token
    let token = sessionStorage.getItem('token');
    if (token) {
      req.headers.Authentication = token;
    }
    if (req.method === 'post' && req.data) {
      let newData = new Array();
      Object.keys(req.data).forEach((key) => {
        if (req.data[key]) {
          newData.push(key + '=' + req.data[key]);
        }
      });
      req.data = newData.join('&');
    }
    return req;
  },
  (error) => {
    //页面抛出错误
    Promise.reject(error);
  },
);

newIntances.interceptors.response.use(
  (req) => {
    return req.data ? req.data : req.status;
  },
  (error) => {
    const response = error.response;
    if (response) {
      switch (response.status) {
        case 400:
          message.error('参数异常');
          break;
        case 401:
          message.error('身份过期，请重新登录');
          localStorage.removeItem('token');
          localStorage.removeItem('userInfo');
          history.push('/login');
          break;
        case 404:
          message.error('请求路径失败');
          break;
        case 500:
          message.error('服务器异常！请联系管理员');
          break;

        default:
          message.error('未知错误');
          break;
      }
    }
    return Promise.reject('自定义错误');
  },
);
export default newIntances;
